package juc.atomic;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @author fangbin
 * @desc 演示AtomicIntegerFieldUpdater的升级，score不能是static或者是私有的
 * @date 2020/6/15 20:07
 */
public class AtomicIntegerFieldUpdaterDemo implements Runnable{
    static Candidate tom;
    static Candidate peter;
    public static AtomicIntegerFieldUpdater<Candidate>  scoreUpdater =
            AtomicIntegerFieldUpdater.newUpdater(Candidate.class,"score");

    @Override
    public void run() {
        for(int i=0;i<10000;i++){
            tom.score++;
            scoreUpdater.getAndIncrement(peter);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        tom = new Candidate();
        peter = new Candidate();
        AtomicIntegerFieldUpdaterDemo atomicIntegerFieldUpdaterDemo =
                new AtomicIntegerFieldUpdaterDemo();
        Thread t1 = new Thread(atomicIntegerFieldUpdaterDemo);
        Thread t2 = new Thread(atomicIntegerFieldUpdaterDemo);
        Thread t3 = new Thread(atomicIntegerFieldUpdaterDemo);
        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t2.join();
        t3.join();
        System.out.println(tom.score);
        System.out.println(peter.score);
    }
    public static class Candidate{
         volatile  int score;
    }
}
